package br.com.felix.fwt.ui;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import org.apache.log4j.Logger;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;

import br.com.felix.fwt.log.LoggerFactory;
import br.com.felix.fwt.ui.exception.ComponentRenderException;

public class Chart extends BaseComponent{

    private static final long serialVersionUID = 5865254259453010722L;
    
    private static Logger logger = LoggerFactory.getLogger(Chart.class);

    private JFreeChart chart;
    private int width;
    private int height;
    private static File outputDirectory = null;
    private static boolean writeToFilesystem = false;
    
    {
        this.cssClass = "fwtchart";
    }
    
    public Chart(JFreeChart chart, int width, int height){
        this.chart = chart;
        this.width = width;
        this.height = height;
    }

    @Override
    public void write(PrintWriter out) throws ComponentRenderException {
        String name = getName();
        if(writeToFilesystem){
            String fileName = name + ".png";
            File file = new File(outputDirectory,fileName);
            logger.debug("Saving chart to filesystem at:"+file.getAbsolutePath());
            try {
                ChartUtilities.saveChartAsPNG(file, chart, width, height);
            } 
            catch (IOException e) {
                String msg = "Could not render chart. An IOException ocurred during chart generation.";
                logger.error(msg, e);
                throw new ComponentRenderException(msg, e);
            }
            out.printf("<img src=\"%s\" width=\"%s\" height=\"%s\" alt=\"%s\"/>",fileName, width, height, chart.getTitle().getText());
        }
        else{
            Form form = getExecutingForm();
            String link = form.getClass().getSimpleName()+"?actionName=CHART&chart="+name;
            out.printf("<img src=\"%s\" width=\"%s\" height=\"%s\" alt=\"%s\"/>",link, width, height, chart.getTitle().getText());
        }
    }

    public JFreeChart getChart() {
        return chart;
    }

    public int getWidth() {
        return width;
    }

    public Chart setWidth(int width) {
        this.width = width;
        return this;
    }

    public int getHeight() {
        return height;
    }

    public Chart setHeight(int height) {
        this.height = height;
        return this;
    }

    public static void writeTo(File fileOutputDirectory) {
        if(fileOutputDirectory==null){
            writeToFilesystem = false;
        }
        else{
            writeToFilesystem = true;
            outputDirectory = fileOutputDirectory;
        }
    }

    
    public void updateChart(JFreeChart chart, int width, int height){
        this.chart = chart;
        this.width = width;
        this.height = height;
    }
}
